# -*- coding: utf-8 -*-

# Copyright (c) 2011, Sergey Karakovskiy, Nikolay Sohryakov
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of Yasker nor the
#       names of its contributors may be used to endorse or promote products
#       derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import atexit
import json
import logging
import threading
import xmpp
import core


__author__ = 'Nikolay Sohryakov, Sergey Karakovskiy'
__copyright__ = 'Copyright 2011, Yasker'
__license__ = 'New BSD'
__email__ = 'Nikolay.Sohryakov+yasker@gmail.com, Sergey.Karakovskiy+yasker@gmail.com'

__all__ = ['connect', 'disconnect', 'send']

_xmpp_thread = None
_xmpp_client = None
_xmpp_client_lock = threading.Lock()

_incoming_callback = None


def register_incoming_callback(callback):
	global _incoming_callback
	_incoming_callback = callback


def connect(connection_details):
	"""
	Connects to the XMPP server. If succeed returns True, otherwise False.

	connection_details -- dict with fields:
		jid : str -- jabber ID
		pwd : str -- password
		host : str -- host address
		port : int -- port
	"""
	global _xmpp_client
	global _xmpp_thread
	global _incoming_callback
	print 'connect, xmpp_service.py; core.events_queue: ', core.events_queue
	if _incoming_callback is None:
		logging.error('_incoming_callback is None')
		return False
	jid = xmpp.protocol.JID(connection_details['jid'])
	_xmpp_client = xmpp.Client(jid.getDomain(), debug=[])
	logging.info('Attempting to connect')
	_xmpp_connection = _xmpp_client.connect(
			(connection_details['host'], connection_details['port']))
	if not _xmpp_connection:
		logging.error('Error while trying to connect with %s' %
		              _xmpp_connection)
		return False
	logging.info('Connected with %s' % _xmpp_connection)
	auth = _xmpp_client.auth(jid.getNode(), connection_details['pwd'],
	                         'yasker')
	if not auth:
		logging.error('Could not authenticate')
		return False
	logging.info('Authenticated')
	_xmpp_client.RegisterHandler('message', _incoming)
	_xmpp_client.sendInitPresence(requestRoster=0)
	logging.info('Online')
	_xmpp_thread = threading.Thread(target=_xmpp_loop, args=(
		_xmpp_client, _xmpp_client_lock), name='XMPP Thread')
	_xmpp_thread.setDaemon(True)
	_xmpp_thread.start()
	return True


def disconnect():
	"""
	Disconnect from the XMPP server.
	"""
	global _xmpp_client
	global _xmpp_client_lock

	if _xmpp_client_lock.acquire():
		if _xmpp_client is not None and _xmpp_client.isConnected():
			_xmpp_client.disconnect()
			logging.info("XMPP disconnected")
	else:
		logging.error("xmpp_disconnect: unable to set lock")


def _incoming(connection, xmpp_message):
	"""
	A function that is being called when a new message is received.
	"""
	logging.debug('message received: %s', xmpp_message.getBody())
	if _incoming_callback is None:
		logging.error('_incoming_callback is None')
	else:
	#		core.events_queue.put(_incoming_callback(xmpp_message.getBody()))
		_incoming_callback(xmpp_message.getBody())


def send(jid_to, yasker_request):
	"""
	Send a request over XMPP.
	"""
	global _xmpp_client
	global _xmpp_client_lock
	if not _xmpp_client_lock.acquire():
		logging.error("send_over_xmpp: lock is not acquired")
		return
	if isinstance(yasker_request, dict):
		xmpp_body = json.dumps(yasker_request)
	else:
		xmpp_body = yasker_request
	jid = xmpp.protocol.JID(jid_to)
	logging.debug('send_over_xmpp: sending a message: %s' % yasker_request)
	_xmpp_client.send(xmpp.protocol.Message(jid, body=xmpp_body, typ='chat'))
	_xmpp_client_lock.release()


def _xmpp_loop(connection, lock):
	"""
	Worker function for the thread to check for new XMPP messages.
	"""
	while connection is not None:
		if lock.acquire():
			connection.Process(0.04)
			lock.release()


#call function xmpp_disconnect when the module is about to be destroyed
atexit.register(disconnect)
